package role

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"go-admin/base/dao"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateLogic) Update(req *types.RoleUpdateReqDTO) (resp *types.RoleBooleanRespDTOS, err error) {
	role, err := l.svcCtx.RoleModel.FindOneByName(l.ctx, req.RoleName)
	if err != nil {
		if err != sqlc.ErrNotFound {
			_ = fmt.Errorf(err.Error())
			return nil, err
		}
	} else {
		if role.Id != req.RoleID {
			return &types.RoleBooleanRespDTOS{
				Data: false,
				Result: types.Result{
					Code:    444,
					Message: "角色已存在！" + req.RoleName,
				},
			}, nil
		}
	}

	if err = l.svcCtx.RoleModel.Update(l.ctx, &dao.Role{
		Id:   req.RoleID,
		Name: sql.NullString{String: req.RoleName, Valid: true},
	}); err != nil {
		_ = fmt.Errorf(err.Error())
		return nil, err
	}

	return &types.RoleBooleanRespDTOS{
		Data: true,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
